import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-23
 * Time: 9:07
 */
class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;
    private long time;
    public MyTimerTask(Runnable runnable, long time){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
    public void run(){
        runnable.run();
    }
    public long getTime(){
        return time;
    }
}
public class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private static Object locker = new Object();
    public MyTimer(){
        Thread t = new Thread(()->{
            try {
                while (true) {
                    synchronized (locker) {
                        MyTimerTask task = queue.peek();
                        while (task == null) {
                            locker.wait();
                            task = queue.peek();
                        }
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task.getTime()) {
                            task.run();
                            queue.poll();
                        } else {
                            locker.wait(task.getTime() - curTime);
                        }
                    }
                }
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        });
        t.start();
    }
    private void schedule(Runnable runnable, long delay){
        synchronized (locker){
            MyTimerTask myTimerTask = new MyTimerTask(runnable, delay);
            queue.add(myTimerTask);
            locker.notify();
        }
    }

    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(()->{
            System.out.println("hello 3000");
        }, 3000);

        myTimer.schedule(()->{
            System.out.println("hello 2000");
        }, 2000);

        myTimer.schedule(()->{
            System.out.println("hello 1000");
        }, 1000);

    }

}
